<!-- 发日常贴 -->
<template>
  <view class="content">
    <div> <!-- 返回按钮 -->
      <button class="back_button" @click="goBack()" plain="true">
        <image src="/static/icon/back1.png" mode="aspectFill" style="height: 50px; width: 50px; border: none;"></image>
      </button>
    </div>
    <form @submit="formSubmit" @reset="formReset" style="position: absolute; top: 10%; width: 350px;">
      <div> <!-- 帖子类型 -->
        <label><text>帖子类型：</text></label>
        <picker @change="handlePickerChange" :value="index" :range="kindList" range-key="name">
          <view class="picker">
            {{ kindList[index].name }}
          </view>
        </picker>
      </div>
      <div> <!-- 内容 -->
        <textarea v-model="e_content" name="content" placeholder=" 请输入内容:" maxlength="300" cols="100"
          rows="200"></textarea>
      </div>
      <!-- 上传图片 -->
      <div style="width: 350px;">
        <button @click="chooseImage()" style="">上传图片（至多六张）</button>
        <image v-for="(url, index) in imageUrls" :src="url" :key="index" style="height: 80px;width: 80px;">
        </image>
      </div>
      <div>
        <button form-type="submit">发布</button>
        <button type="default" form-type="reset">重置</button>
      </div>
    </form>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        e_content: '',
        kindList: [{
            name: "日常分享",
            id: 1
          },
          {
            name: "技能提升",
            id: 2
          },
          {
            name: "吐槽",
            id: 3
          }
        ],
        index: 0,
        imageUrls: [], // 存储已选择的图片路径
        formimageUrls: '', //随表单上传的字符串
        imageCount: 0, //待上传图片数量
        uploadUrl: 'http://localhost:8081/upload/blog/' + false, // 图片上传地址
      };
    },
    methods: {
      handlePickerChange: function(e) { //更新选择器下标
        this.index = e.detail.value;
      },
      formSubmit: function(e) {
        getApp().globalData.blogType = this.index //获取当前选择类型下标（全局变量）
        var formData = {
          content: this.e_content,
          images: this.formimageUrls
        };
        var jsonData = JSON.stringify(formData); //将表单数据转换成json类型数据
        console.log(formData);
        wx.showToast({
          title: '发布中ing',
          icon: 'loading',
          mask: true,
          duration: 100000,
          success: function() {
            //弹窗后执行，可以省略
          }
        })

        uni.request({ //上传表单内容
          url: 'http://localhost:8081/blog/daily/publish/' + getApp().globalData.blogType, //不同帖子类型发往后端不同地址
          data: jsonData,
          header: {
            'Content-Type': 'application/json', //自定义请求头信息
            'Access-Control-Allow-Headers': 'appId',
            'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
            'Access-Control-Max-Age': 86400,
            'Authorization': '' + wx.getStorageSync('sessionID')
          },
          method: 'POST',
          success: res => {
            // console.log(res.data);
            wx.showToast({
              title: '发布成功',
              icon: 'success',
              mask: true,
              duration: 1500,
              success: function() {
                //弹窗后执行，可以省略
                setTimeout(function() {
                  wx.navigateBack()
                }, 1500);
              }
            })
          }
        });
      },
      formReset: function(e) {
        console.log('清空数据')
      },
      chooseImage() {
        uni.chooseImage({
          count: 6, // 可以选择的图片数量
          success: (res) => {
            this.imageUrls = res.tempFilePaths; // 将选择的图片路径保存起来
            console.log(this.imageUrls)
            this.imageCount = this.imageUrls.length
            console.log(this.imageCount)
            this.uploadImages()
          },
          fail: (err) => {
            console.log(err);
          },
        });
      },
      uploadImages() {
        wx.showToast({
          title: '上传图片中',
          icon: 'loading',
          mask: true,
          duration: 100000,
          success: function() {
            //弹窗后执行，可以省略
          }
        })

        this.imageUrls.forEach((path) => {
          uni.uploadFile({
            url: this.uploadUrl,
            filePath: path,
            name: 'file',
            formData: {}, // 如果需要传递其他参数，可以在这里设置formData
            header: {
              'Content-Type': 'multipart/form-data', //自定义请求头信息
              'Access-Control-Allow-Headers': 'appId',
              'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
              'Access-Control-Max-Age': 86400,
              'Authorization': '' + wx.getStorageSync('sessionID')
            },
            success: (res) => {
              console.log(res)
              if (res.statusCode === 200) {
                console.log('图片上传成功' + res.data);
                if (this.formimageUrls == '') {
                  this.formimageUrls = this.formimageUrls.concat(res.data)
                } else {
                  this.formimageUrls = this.formimageUrls.concat(',' + res.data)
                }
                this.imageCount--;
                if (this.imageCount == 0) {
                  wx.showToast({
                    title: '上传成功',
                    icon: 'success',
                    duration: 1500,
                    mask: true,
                    success: function() {}
                  })
                }
              }
            },
            fail: (err) => {
              console.log(err);
              console.log('图片上传失败')
            },
          });
        });
      },
      goBack() { //返回上个页面
        uni.navigateBack();
      },
    }
  }
</script>

<style>
  page {
    height: 100vh;
    width: 100vw;
  }

  .back_button {
    position: absolute;
    border: none !important;
    border-color: transparent;
    right: 0%;
    top: 0%;
  }

  picker {
    display: inline-block;
    vertical-align: middle;
    z-index: 9999;
    /* 最上层 */
    width: 200px;
    height: 30px;
    line-height: 30px;
    border: 1px solid #acacac;
    border-radius: 4px;
    text-align: center;
    background-color: #ffffff;
    margin-bottom: 15px;
    margin-left: 15px;
  }

  label {
    border: 1px solid #acacac;
    border-radius: 4px;
    background-color: #ffffff;
    height: 30px;
    width: 80px;
    text-align: center;
  }

  textarea {
    border: 1px solid #acacac;
    border-radius: 10px;
    display: inline-block;
    vertical-align: top;
    margin-left: 5px;
    background-color: #ffffff;
    height: 300px;
  }

  button {
    background-color: #00aa00;
    color: white;
    padding: 5px 15px;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    width: 220px;
    /* 设置按钮宽度 */
    height: 55px;
    /* 设置按钮高度 */
    margin-top: 10px;
  }

  .content {
    background-image: url();
    /* 图片素材background_2.jpg */
    background-size: cover;
    height: 100vh;
    width: 100vw;

    display: flex;
    /* 弹性布局 */
    flex-direction: column;
    /* 设置从上往下布局 */
    align-items: center;
    /* 水平居中 */
    justify-content: center;
    /* 垂直居中 */
  }
</style>